package com.siss.tenancy.util;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Map转换
 * 
 * @author yingw
 * @version 1.0
 */
public class MapUtils {
	
	public static final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	
	/**
	 * Map转Bean
	 * 支持Map嵌套转换
	 * 支持Date类型转换处理
	 * 支持Boolean类型转换处理
	 * 
	 * @param map
	 * @param clazz
	 * @return
	 */
	public static Object mapToBean(Map<?, ?> map, Class<?> clazz){
		
		if(map == null){
			
			return null;
			
		}
		
		try {
			Object object = clazz.newInstance();
			Field[] fields = clazz.getDeclaredFields(); 
			
			for(Field field : fields){
				field.setAccessible(true);
				String name = field.getName(); 
				if(map.containsKey(name)){ // 名称相同
					Object value = map.get(name);
					if(value != null){
						if(field.getType().isInstance(value)){ //判断是否为该类实例,子类实例,接口实现类实例..
							try {
								field.set(object, value);
							} catch (IllegalArgumentException | IllegalAccessException e) {
								e.printStackTrace();
							}
						}else if(value instanceof Map){ // 成员 map to bean
							Object subObject = mapToBean((Map<?, ?>)value, field.getType());
							field.set(object, subObject);
						}else if(field.getType() == Date.class){ // 日期类型处理
							Date date = null; // 目标Date
							//long(13位时间戳) 转 Date
							if(value.getClass() == Long.class){
								Long time = (Long) value;
								date = new Date(time);
							}
							//string(yyyy-MM-dd HH:mm:ss) 转 Date
							if(value.getClass() == String.class){
								String time = (String) value;
								try {
									date = format.parse(time);
								} catch (Exception e) {
								}
							}
							try {
								field.set(object, date);
							} catch (IllegalArgumentException | IllegalAccessException e) {
								e.printStackTrace();
							}
						}else if(field.getType() == Boolean.class){ // 布尔类型处理
							// int 转 boolean
							if(value.getClass() == Integer.class){
								Integer intValue = (Integer) value;
								field.set(object, intValue == 1 ? true : false);
							}
							
						}else if(field.getType() == String.class){
							if(value.getClass() == Integer.class){
								field.set(object, value+"");
							}
						}
					}
				}
			}
			
			return object;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
}


